# タイによるスカラーの監視
package MonScalar;

sub TIESCALAR {
    my ($pkg, $name, $value) = @_;
    my $obj = { name => $name, value => $value };
    bless $obj, $pkg;
    $obj;
}

sub FETCH {
    my $obj = shift;
    print 'Read : $', $obj->{'name'}, " -> $obj->{'value'}\n";
    $obj->{'value'};
}

sub STORE {
    my ($obj, $new_value) = @_;
    print 'Write : $', $obj->{'name'}," <- $new_value\n";
    $obj->{'value'} = $new_value;
}

sub DESTROY {
    my $obj = shift;
    if( $obj->{'name'} ne '__UNMONITOR__' ){
	print 'DESTORY $', "$obj->{'name'}\n";
    }
}


sub unmonitor {
    my ($pkg, $rvar) = @_;
    my $last_value;
    {
	my $obj = tied $$rvar;
	$last_value = $obj->{'value'};
	$obj->{'name'} = '__UNMONITOR__'
    }
    untie $$rvar;
    $$rvar = $last_value;
}


package main;

$x = 10;
tie $x, 'MonScalar', 'x', $x;

$y = $x;
print "y -> $y\n";

$x = 100;
$z = $x;
print "z -> $z\n";

MonScalar->unmonitor( \$x );

print "x -> $x\n";

{
    my $x1 = 100;
    tie $x1, 'MonScalar', 'x1', $x1;
    $x1 = 1000;
}

# end of file;
